package com.yueya.system.controller;

import com.yueya.auth.config.AuthConstant;
import com.yueya.auth.config.AuthProperties;
import com.yueya.auth.session.SessionDao;
import com.yueya.common.base.BaseController;
import com.yueya.common.web.RestPage;
import com.yueya.common.web.RestResult;
import com.yueya.system.dao.tables.TokenManage;
import com.yueya.system.dao.tables.pojos.TokenManageDO;
import com.yueya.system.service.SysTokenService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.Oneway;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yueya.auth.config.AuthConstant.ATTRIBUTE_LOGIN_NAME;

@RestController
@RequestMapping("${auth.adminPath}/session")
public class SessionController extends BaseController {

    @Autowired
    private SessionDao sessionDao;
    @Autowired
    AuthProperties properties;

    @Autowired
    private SysTokenService tokenService;
    @RequiresPermissions("sys:session:list")
    @RequestMapping("page")
    public RestResult listActiveSessions(@RequestParam(name = "limit",defaultValue = "10") int limit,
                                         @RequestParam(name = "offset",defaultValue = "0") int offset){
        if (properties.isJwtMode()) {
            List<TokenManageDO> list = tokenService.page(limit,offset,new TokenManageDO());
            List<Map<String,Object>> result = list.stream().map(item -> {
                Map<String,Object> map = new HashMap<>();
                map.put("id", item.getTokenId());
                map.put("loginName", item.getLoginName());
                map.put("host", item.getHost());
                map.put("startTimestamp", item.getCreateGmt());
                map.put("lastAccessTime", item.getLastCheckTime());
                return map;
            }).collect(Collectors.toList());
            long count = tokenService.countByCondition(new TokenManageDO());
            return RestResult.OKWithPage(result,count);
        }
        RestPage page = sessionDao.getActiveSessions(offset,limit);
        List<Session> sessions = (List<Session>)page.getRows();
        List<Map<String,Object>> result = sessions.stream().map(item -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("loginName", item.getAttribute(ATTRIBUTE_LOGIN_NAME));
            map.put("host", item.getHost());
            map.put("startTimestamp", item.getStartTimestamp());
            map.put("lastAccessTime", item.getLastAccessTime());
            return map;
        }).collect(Collectors.toList());
        return RestResult.OKWithPage(result, page.getCount());
    }
    @RequiresPermissions("sys:session:edit")
    @RequestMapping("forceLogout")
    public RestResult forceLogout(@RequestParam("sessionId") String sessionId){
        try {
            /*
            String curSessionId = SecurityUtils.getSubject().getSession().getId().toString();
            if (curSessionId.equals(sessionId)) {
                return RestResult.FAILER("不允许退出当前用户");
            }*/
            if (properties.isJwtMode()) {
                tokenService.expireToken(sessionId);
            } else {
                Session session=sessionDao.readSession(sessionId);
                session.setAttribute(AuthConstant.FORCE_LOGOUT_KEY,true);
            }
            return RestResult.OK("success");
        } catch (UnknownSessionException e) {
            logger.error("forceLogout err",e);
            return RestResult.ERROR("强制退出失败");
        }
    }
}
